export function timeFix () {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome () {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

export function isEmptyStr(value) {
  let str;
  if (value == null || value == undefined) {
    str = value;
  } else {
    str = value + '';
  }
  if (str == null || str == 'null' || str == undefined || str == 'undefined' || str.match(/^[\s]*$/)) {
    return true;
  } else {
    return false;
  }
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent () {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader (callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {}
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate (id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}

export const startWith = (str, prefix) => {
  const reg = new RegExp('^' + prefix)
  return reg.test(str)
}

export const endWith = (str, suffix) => {
  const reg = new RegExp(suffix + '$')
  return reg.test(str)
}

export const hasChild = (item) => {
  return item.children && item.children.length !== 0
}

/**
 *  验证url
 * @param str_url
 * @returns {boolean}
 */
export const isURL = (url) => {
  const strRegex = '((https|http|ftp|rtsp|mms)?://)'
  const re = new RegExp(strRegex)
  return re.test(url)
}

export const setDocumentTitle = function (title) {
  document.title = title
  const ua = navigator.userAgent
  // eslint-disable-next-line
  const regex = /\bMicroMessenger\/([\d\.]+)/
  if (regex.test(ua) && /ip(hone|od|ad)/i.test(ua)) {
    const i = document.createElement('iframe')
    i.src = '/favicon.ico'
    i.style.display = 'none'
    i.onload = function () {
      setTimeout(function () {
        i.remove()
      }, 9)
    }
    document.body.appendChild(i)
  }
}

/**
 * 判断终端以及浏览器
 * userAgent string User-Agent信息
 */
export const readUserAgent = (ua) => {
  const data = {
    terminal: '',
    browser: '',
    terminalType: {}
  }
  data.terminalType = {
    trident: ua.indexOf('Trident') > -1, // IE内核
    presto: ua.indexOf('Presto') > -1, // opera内核
    webKit: ua.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核
    gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') == -1, // 火狐内核
    mobile: !!ua.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
    ios: !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
    android: ua.indexOf('Android') > -1 || ua.indexOf('Adr') > -1, // android终端
    iPhone: ua.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
    iPad: ua.indexOf('iPad') > -1, // 是否iPad
    webApp: ua.indexOf('Safari') == -1, // 是否web应该程序，没有头部与底部
    weixin: ua.indexOf('MicroMessenger') > -1, // 是否微信 （2015-01-22新增）
    qq: ua.match(/\sQQ/i) == ' qq' // 是否QQ
  }
  if (data.terminalType.ios || data.terminalType.iPhone || data.terminalType.iPad) {
    data.terminal = '苹果'
  } else if (data.terminalType.android) {
    data.terminal = '安卓'
  } else {
    data.terminal = 'PC'
  }
  if (/msie/i.test(ua) && !/opera/.test(ua)) {
    data.browser = 'IE'
  } else if (/firefox/i.test(ua)) {
    data.browser = 'Firefox'
  } else if (/chrome/i.test(ua) && /webkit/i.test(ua) && /mozilla/i.test(ua)) {
    data.browser = 'Chrome'
  } else if (/opera/i.test(ua)) {
    data.browser = 'Opera'
  } else if (/iPad/i.test(ua)) {
    data.browser = 'iPad'
  } else if (/webkit/i.test(ua) && !(/chrome/i.test(ua) && /webkit/i.test(ua) && /mozilla/i.test(ua))) {
    data.browser = 'Safari'
  } else {
    data.browser = '未知'
  }
  return data
}

/*
 * 获取浏览器版本信息
 */
export function getBrowerInfo () {
  const userAgent = window.navigator.userAgent.toLowerCase()
  let browserType = ''
  let browserVersion = ''
  // 浏览器类型-IE
  if (userAgent.match(/msie/) != null || userAgent.match(/trident/) != null) {
    browserType = 'ie'
    browserVersion = getIeVersion()
  } else if (window.opera || (userAgent.indexOf('opr') > 0)) {
    // 欧朋
    browserType = 'opr'
    browserVersion = getOperaVersion(userAgent)
  } else if (userAgent.indexOf('ubrowser') > 0) {
    browserType = 'uc'
    browserVersion = userAgent.match(/ubrowser\/([\d.]+)/)[1]
  } else if (userAgent.indexOf('bidubrowser') > 0) {
    // 百度
    browserType = 'baidu'
    browserVersion = userAgent.match(/bidubrowser\/([\d.]+)/)[1]
  } else if (userAgent.indexOf('metasr') > 0 || userAgent.indexOf('se 2.x') > 0) {
    // 搜狗
    browserType = 'metasr'
    // browserVersion =  userAgent.match(/metasr\/([\d.]+)/)[1]
  } else if (userAgent.indexOf('tencenttraveler') > 0) {
    browserType = 'qq'
    browserVersion = userAgent.match(/tencenttraveler\/([\d.]+)/)[1]
  } else if (userAgent.indexOf('qqbrowser') > 0) {
    browserType = 'qq'
    browserVersion = userAgent.match(/qqbrowser\/([\d.]+)/)[1]
  } else if (userAgent.indexOf('maxthon') > 0) {
    // 遨游
    browserType = 'maxthon'
    browserVersion = userAgent.match(/maxthon\/([\d.]+)/)[1]
  } else if (userAgent.indexOf('firefox') > 0) {
    // 火狐
    browserType = 'firefox'
    browserVersion = userAgent.match(/firefox\/([\d.]+)/)[1]
  } else if (userAgent.indexOf('edge') > 0) {
    // edge
    browserType = 'edge'
    browserVersion = userAgent.match(/edge\/([\d.]+)/)[1]
  } else if (userAgent.indexOf('chrome') > 0) {
    // 谷歌/360
    if (validate360('type', 'application/x360mmplugin')) {
      browserType = '360'
      // browserVersion =  userAgent.match(/chrome\/([\d.]+)/)[1]
    } else {
      browserType = 'chrome'
      browserVersion = userAgent.match(/chrome\/([\d.]+)/)[1]
    }
  } else if (userAgent.indexOf('Safari') > -1) {
    // 苹果
    browserType = 'safari'
    browserVersion = userAgent.match(/version\/([\d.]+)/)[1]
  } else {
    browserType = 'other'
  }
  const browser = {}
  browser.browserType = browserType
  browser.browserVersion = browserVersion
  return browser
}
/*
 * 判断是否为360浏览器
 */
export function validate360 (option, value) {
  const mimeTypes = window.navigator.mimeTypes
  for (const mt in mimeTypes) {
    if (mimeTypes[mt][option] === value) {
      return true
    }
  }
  return false
}
/*
 * 获取IE浏览器版本
 */
export function getIeVersion () {
  const IEMode = document.documentMode
  const rMsie = /(msie\s|trident.*rv:)([\w.]+)/
  const ma = window.navigator.userAgent.toLowerCase()
  const match = rMsie.exec(ma)
  try {
    return match[2]
  } catch (e) {
    return IEMode
  }
}
/*
 * 获取oper浏览器版本
 */
export function getOperaVersion (userAgent) {
  try {
    if (window.opera) {
      return userAgent.match(/opera.([\d.]+)/)[1]
    } else if (userAgent.indexOf('opr') > 0) {
      return userAgent.match(/opr\/([\d.]+)/)[1]
    }
  } catch (e) {
    return 0
  }
}
/**
 * 通用js方法封装处理
 * Copyright (c) 2019 ruoyi
 */

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
  let search = params;
  search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
  dateRange = Array.isArray(dateRange) ? dateRange : [];
  if (typeof (propName) === 'undefined') {
    search.params['beginTime'] = dateRange[0];
    search.params['endTime'] = dateRange[1];
  } else {
    search.params['begin' + propName] = dateRange[0];
    search.params['end' + propName] = dateRange[1];
  }
  return search;
}

// 回显数据字典
export function selectDictLabel(datas, value) {
  var actions = [];
  Object.keys(datas).some((key) => {
    if (datas[key].value == ('' + value)) {
      actions.push(datas[key].label);
      return true;
    }
  })
  return actions.join('');
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
  if(value === undefined) {
    return "";
  }
  var actions = [];
  var currentSeparator = undefined === separator ? "," : separator;
  var temp = value.split(currentSeparator);
  Object.keys(value.split(currentSeparator)).some((val) => {
    Object.keys(datas).some((key) => {
      if (datas[key].value == ('' + temp[val])) {
        actions.push(datas[key].label + currentSeparator);
      }
    })
  })
  return actions.join('').substring(0, actions.join('').length - 1);
}

// 字符串格式化(%s )
export function sprintf(str) {
  var args = arguments, flag = true, i = 1;
  str = str.replace(/%s/g, function () {
    var arg = args[i++];
    if (typeof arg === 'undefined') {
      flag = false;
      return '';
    }
    return arg;
  });
  return flag ? str : '';
}

// 转换字符串，undefined,null等转化为""
export function parseStrEmpty(str) {
  if (!str || str == "undefined" || str == "null") {
    return "";
  }
  return str;
}

// 数据合并
export function mergeRecursive(source, target) {
  for (var p in target) {
    try {
      if (target[p].constructor == Object) {
        source[p] = mergeRecursive(source[p], target[p]);
      } else {
        source[p] = target[p];
      }
    } catch (e) {
      source[p] = target[p];
    }
  }
  return source;
};

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
  let config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    //  == null
    if (!childrenListMap[parentId]) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      if (!!childrenListMap[o[config.id]]) {
        o[config.childrenList] = childrenListMap[o[config.id]];
      }
    }

    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && typeof (value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && typeof (value[key]) !== 'undefined') {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result
}

export function numFormat(num, rates = 1000, fixed = 2) {
  if (!num) {
    return '0'
  } else if (num > rates) {
    return (num / rates).toFixed(fixed)
  } else {
    return num
  }
}

// 验证是否为blob格式
export async function blobValidate(data) {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}

// 防抖
export function debounce(fn, delay) {
  var timeout = null;
  return function(...args) {
    if(timeout !== null)   clearTimeout(timeout);
    timeout = setTimeout(fn.bind(this), delay, ...args);
  }
}

// 脱敏
export function hideCode(val) {
  if(val){
    if(val.length){
      const len = val.length
      if(len === 1){
        return '*';
      }else if(len === 2){
        return val[0] + '*';
      }else if(len === 3){
        return val[0] + '*' + val[2];
      }else if(len>3 && len <6){
        const newVal = val.substring(2,len-1);
        let newValChange = []
        for(let i =0 ;i<newVal.length;i++){
          newValChange.push('*');
        }
        return val[0]+val[1]+newValChange.join('')+val[len-1]
      }else if(len >= 6 && len <= 8){
        const newVal = val.substring(2,len-2);
        let newValChange = []
        for(let i =0 ;i<newVal.length;i++){
          newValChange.push('*');
        }
        return val[0]+val[1]+newValChange.join('')+val[len-2]+val[len-1]
      }else{
        const newVal = val.substring(3,len-3);
        let newValChange = []
        for(let i =0 ;i<newVal.length;i++){
          newValChange.push('*');
        }
        return val[0]+val[1]+val[2]+newValChange.join('')+val[len-3]+val[len-2]+val[len-1]
      }
    }
  }

}

// 遍历tree
const traverseTree = (trees, callback) => {
  const datas = expandTree(trees, [])
  datas.forEach((e) => {
    callback(e)
  })
}

// 展开tree
const expandTree = (trees, datas) => {
  datas = datas || []
  const expand = (data) => {
    datas.push(data)
    if (Array.isArray(data.children) && data.children.length > 0) {
      data.children.forEach((item) => {
        expandTree(item, datas)
      })
    }
  }
  if (Array.isArray(trees)) {
    trees.forEach((item) => {
      expand(item)
    })
  } else {
    expand(trees)
  }
  return datas
}

// 过滤tree
const filterTree = (trees, callback) => {
  const deepFilter = (list) => {
    if (Array.isArray(list)) {
      return list.filter((item) => {
        if (Array.isArray(list.children) && list.children.length > 0) {
          item.children = deepFilter(item.children)
        }
        return callback(item)
      })
    } else {
      if (Array.isArray(list.children) && list.children.length > 0) {
        list.children = deepFilter(list.children)
      }
      return callback(list) ? list : null
    }
  }
  return deepFilter(trees)
}

export default {
  list: (trees) => {
    trees = JSON.parse(JSON.stringify(trees))
    const datas = expandTree(trees, [])
    datas.forEach((item) => {
      item.children && delete item.children
    })
    return datas
  },
  find: (trees, callback) => {
    return expandTree(trees, []).find((e) => callback(e))
  },
  filter: (trees, callback) => {
    return filterTree(trees, callback)
  },
  forEach: (trees, callback) => {
    traverseTree(trees, callback)
  }
}
